import { useState, useEffect } from "react";
import ChatPanel from "./components/ChatPanel";
import { groupInfo, contacts, initialMessages } from "./data";

const App = () => {
  const currentUserId = "lebei";
  const currentGroupId = "pingyu";

  const [groupMessages, setGroupMessages] = useState<
    typeof initialMessages.pingyu
  >([]);

  useEffect(() => {
    setTimeout(() => {
      setGroupMessages(initialMessages[currentGroupId]);
    }, 100);
  }, [currentGroupId]);

  const handleSendMessage = (message: string) => {
    if (!message.trim()) return;
    const newMessage = {
      id: `msg-${Date.now()}`,
      senderId: currentUserId,
      content: message,
      timestamp: new Date(),
    };
    setGroupMessages((prevMessages) => [...prevMessages, newMessage]);
  };

  useEffect(() => {
    const currentGroup = groupInfo[currentGroupId];
    if (!currentGroup) return;
    const otherMembers = currentGroup.members.filter(
      (id) => id !== currentUserId
    );
    const interval = setInterval(() => {
      if (Math.random() > 0.7) {
        const randomSender =
          otherMembers[Math.floor(Math.random() * otherMembers.length)];
        const messages = [
          "好啊，到时候见！",
          "我可能会晚点到",
          "需要带拍子吗？",
          "记得带水",
          "大家注意防晒",
          "场地费AA吗？",
          "要不要一起吃个饭？",
          "加我一个",
          "收到",
          "我开车过来，谁需要接送？",
        ];
        const newMessage = {
          id: `msg-${Date.now()}`,
          senderId: randomSender,
          content: messages[Math.floor(Math.random() * messages.length)],
          timestamp: new Date(),
        };
        setGroupMessages((prev) => [...prev, newMessage]);
      }
    }, 10000);
    return () => clearInterval(interval);
  }, [currentUserId, currentGroupId]);

  return (
    <ChatPanel
      groupName={groupInfo[currentGroupId].name}
      messages={groupMessages}
      contacts={contacts}
      currentUserId={currentUserId}
      onSendMessage={handleSendMessage}
    />
  );
};

export default App;
